package com.iotechn.unimall.biz.service.lease;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.iotechn.unimall.biz.service.order.OrderBizService;
import com.iotechn.unimall.core.exception.AppServiceException;
import com.iotechn.unimall.core.exception.BizServiceException;
import com.iotechn.unimall.core.exception.ExceptionDefinition;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.data.component.LockComponent;
import com.iotechn.unimall.data.domain.LeaseOrderDO;
import com.iotechn.unimall.data.mapper.LeaseOrderMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class LeaseBizService {

    private static final Logger logger = LoggerFactory.getLogger(OrderBizService.class);

    private static final String ORDER_STATUS_LOCK = "LEASE_ORDER_STATUS_LOCK_";

    @Autowired
    private LockComponent lockComponent;
    @Autowired
    private LeaseOrderMapper leaseOrderMapper;

    public boolean changeOrderStatus(String orderNo, int nowStatus, LeaseOrderDO leaseOrderDO) throws ServiceException {
        try {
            // 防止传入值为空,导致其余订单被改变
            if (orderNo == null || leaseOrderDO == null) {
                throw new BizServiceException(ExceptionDefinition.ORDER_STATUS_CHANGE_FAILED);
            }

            if (lockComponent.tryLock(ORDER_STATUS_LOCK + orderNo, 30)) {
                if (leaseOrderMapper.update(leaseOrderDO,
                        new EntityWrapper<LeaseOrderDO>()
                                .eq("order_no", orderNo)
                                .eq("status", nowStatus)) > 0) {
                    return true;
                }
                throw new BizServiceException(ExceptionDefinition.ORDER_STATUS_CHANGE_FAILED);
            } else {
                throw new BizServiceException(ExceptionDefinition.ORDER_SYSTEM_BUSY);
            }
        } catch (ServiceException e) {
            throw e;
        } catch (Exception e) {
            logger.error("[订单状态扭转] 异常", e);
            throw new BizServiceException(ExceptionDefinition.ORDER_UNKNOWN_EXCEPTION);
        } finally {
            lockComponent.release(ORDER_STATUS_LOCK + orderNo);
        }
    }

    public LeaseOrderDO checkOrderExist(String orderNo, Long userId) throws ServiceException {
        Wrapper<LeaseOrderDO> wrapper = new EntityWrapper<LeaseOrderDO>().eq("order_no", orderNo);
        if (userId != null) {
            wrapper.eq("user_id", userId);
        }
        List<LeaseOrderDO> orderDOS = leaseOrderMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(orderDOS)) {
            throw new AppServiceException(ExceptionDefinition.ORDER_NOT_EXIST);
        }
        return orderDOS.get(0);
    }

}
